import 'dart:collection';

import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:get/get.dart';
import 'package:tiktokadult/assets_tool/app_colors.dart';

import '../../../../hj_utils/widget_utils.dart';
import '../../../../tools_base/debug_log.dart';

class AiH5Page extends StatefulWidget {
  final String? webUrl;
  const AiH5Page({super.key, this.webUrl});

  @override
  State<StatefulWidget> createState() {
    return _YHYSH5ViewState();
  }
}

class _YHYSH5ViewState extends State<AiH5Page> with WidgetsBindingObserver {
  InAppWebViewController? webView;

  bool isFirstLoad = true;
  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this); //添加观察者
  }

  @override
  void dispose() {
    super.dispose();
    WidgetsBinding.instance.removeObserver(this); //销毁观察者
  }

  ///生命周期变化时回调
//  resumed:应用可见并可响应用户操作
//  inactive:用户可见，但不可响应用户操作
//  paused:已经暂停了，用户不可见、不可操作
//  suspending：应用被挂起，此状态IOS永远不会回调
  @override
  void didChangeAppLifecycleState(AppLifecycleState state) async {
    super.didChangeAppLifecycleState(state);
    debugLog("@@@@@@@@@  didChangeAppLifecycleState: $state");

    if (state == AppLifecycleState.resumed) {
      bool canGoBack = await webView?.canGoBack() ?? false;

      if (canGoBack) {
        isFirstLoad = true;

        await webView?.goBack();
      }
    }
  }

  ///当前系统改变了一些访问性活动的回调
  @override
  void didChangeAccessibilityFeatures() {
    super.didChangeAccessibilityFeatures();
    debugLog("@@@@@@@@@ didChangeAccessibilityFeatures");
  }

  /// Called when the system is running low on memory.
  ///低内存回调
  @override
  void didHaveMemoryPressure() {
    super.didHaveMemoryPressure();
    debugLog("@@@@@@@@@ didHaveMemoryPressure");
  }

  /// Called when the system tells the app that the user's locale has
  /// changed. For example, if the user changes the system language
  /// settings.
  ///用户本地设置变化时调用，如系统语言改变
  // @override
  // void didChangeLocales(List<Locale> locale) {
  //   super.didChangeLocales(locale);
  //   debugLog("@@@@@@@@@ didChangeLocales");
  // }

  /// Called when the application's dimensions change. For example,
  /// when a phone is rotated.
  ///应用尺寸改变时回调，例如旋转
  @override
  void didChangeMetrics() {
    super.didChangeMetrics();
    Size size = View.of(context).physicalSize;
    debugLog("@@@@@@@@@ didChangeMetrics  ：宽：${size.width} 高：${size.height}");
  }

  /// {@macro on_platform_brightness_change}
  @override
  void didChangePlatformBrightness() {
    super.didChangePlatformBrightness();
    debugLog("@@@@@@@@@ didChangePlatformBrightness");
  }

  ///文字系数变化
  @override
  void didChangeTextScaleFactor() {
    super.didChangeTextScaleFactor();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Stack(
        fit: StackFit.expand,
        children: [
          InAppWebView(
            initialUrlRequest: URLRequest(url: Uri.parse(widget.webUrl ?? "")), //h5的url
            initialUserScripts: UnmodifiableListView<UserScript>([]),
            onWebViewCreated: (controller) {
              webView = controller;
              //Config.webView = controller;
            },

            onLoadStart: (InAppWebViewController? controller, Uri? url) async {
              debugPrint("onPageFinished$url");
              if (!isFirstLoad) {
                try {
                  // await launchUrl(url!, mode: LaunchMode.externalNonBrowserApplication);
                } catch (e) {
                  debugPrint("print");
                }
              }

              isFirstLoad = false;
            },

            // initialOptions: options,
            // pullToRefreshController: pullToRefreshController,
          ),
          Positioned(
            bottom: 70,
            right: 10,
            width: 44,
            height: 44,
            child: GestureDetector(
              onTap: () => Get.back(),
              child: Container(
                alignment: Alignment.center,
                decoration: BoxDecoration(
                  color: AppColors.primaryHighColor,
                  borderRadius: BorderRadius.circular(22),
                ),
                child: Text(
                  '退出',
                  style: textStyle(14, Colors.black, FontWeight.w500),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
}
